﻿#region Using directives

using System;
using System.Windows.Forms;
using System.Diagnostics;

using ApplicationLibrary.ExtendedControls;

#endregion

using ApplicationLibrary.SqlConnector;

namespace ApplicationLibrary.DBManager
{
    public partial class BatchForm : WeifenLuo.WinFormsUI.Docking.DockContent
    {
        #region Private

        private string formName = string.Empty;

        protected string ConnectionString { get; private set; }

        public ProviderType providerType { get; private set; }

        private DBMode BatchStatus = DBMode.Browse;

        public string Description { get { return tssDescription.Text; } set { tssDescription.Text = value; Application.DoEvents(); } }

        public ToolStripProgressBar ProgressBar { get { return tssProgBar; } }

        private bool userStopBatch;

        protected Control keyControl = null;
        protected DBManager dbManager = null;
        internal ControlBinder controlBinder;

        #endregion

        #region Properties

        public bool IsNew { get; private set; }

        public Control KeyControl { get { return keyControl; } }

        public bool SilentMode { set { if (dbManager != null) dbManager.SilentMode = value; } }

        #endregion

        #region Events & Delegate

        public delegate void PostFormLoadEventHandler(object sender, DBManager dbManager);

        public event PostFormLoadEventHandler PostLoaded;

        public delegate bool ToolbarButtonEventHandler(ToolStripButton sender);

        public delegate bool ToolbarSplitButtonEventHandler(ToolStripSplitButton sender);

        public event ToolbarButtonEventHandler OnEnableToolbarButtons;

        public event ToolbarSplitButtonEventHandler OnEnableToolbarSplitButtons;

        public delegate void OpenFormEventHandler(WeifenLuo.WinFormsUI.Docking.DockContent frm, bool modal);

        public event OpenFormEventHandler OpenForm;

        #endregion

        #region Virtual Function

        protected virtual void OnAttachData()
        {
        }

        protected virtual void OnBatchExecute()
        {
        }

        protected virtual bool OnBeforeBatchExecute()
        {
            return true;
        }

        protected virtual void OnDisableControlsForRun()
        {
        }

        protected virtual void OnBindData()
        {
        }

        #endregion

        public BatchForm()
        {
            InitializeComponent();
        }

        public BatchForm(string formname)
        {
            ConnectionString = GlobalInfo.DBaseInfo.dbManager.DB_ConnectionString;
            this.providerType = GlobalInfo.LoginInfo.ProviderType;
            formName = formname;
            InitializeComponent();
            controlBinder = new ControlBinder();
            OnCustomizeToolbar(tspdbForm);
        }

        protected virtual void OnCustomizeToolbar(ToolStrip toolstrip)
        {
        }

        protected override void OnLoad(EventArgs e)
        {
            OnAttachData();
            if (controlBinder != null)
                controlBinder.Enable(true);

            OnBindData();

            ManageToolbarEvents();
            OnDisableControlsForRun();

            OnAddSplitMenuButton();

            if (PostLoaded != null)
            {
                PostLoaded(this, dbManager);
                ManageOperationButton();
            }
            base.OnLoad(e);
        }

        protected bool UserStopBatch()
        {
            return userStopBatch;
        }

        private void formDB_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Escape)
            {
                e.Handled = true;
            }
        }

        private void formDB_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyData)
            {
                case Keys.F12:
                    if (tbnGo.Enabled)
                        OnGoEvent();
                    break;
            }
        }

        private void formDB_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = OnBeforeClosing();
        }

        /// <summary>
        /// Only For Enable/Disable Controls
        /// </summary>
        public Binding BindControl(Control control)
        {
            controlBinder.Bind(control);
            return null;
        }

        public void ShowDialog(bool visible)
        {
            base.ShowDialog();
            this.Visible = visible;
        }

        #region virtual override function

        protected virtual bool OnBeforeClosing()
        {
            return false;
        }

        protected virtual bool OnPrintDocument(string sender, printerForm pf)
        {
            return true;
        }

        private void OnGoEvent()
        {
            if (OnBeforeBatchExecute())
            {
                userStopBatch = false;
                BatchStatus = DBMode.Run;
                ManageToolbarEvents();
                Application.DoEvents();
                OnBatchExecute();
                BatchStatus = DBMode.Browse;
                ManageToolbarEvents();
                OnDisableControlsForRun();
            }
        }

        private void OnStopEvent()
        {
            userStopBatch = MessageBox.Show("Do you want stop process ?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.Yes;
        }

        #endregion

        #region Enable Disable Controls

        protected virtual void ManageControls(System.Windows.Forms.Control.ControlCollection controls)
        {
            bool enabled = BatchStatus != DBMode.Run;

            foreach (Control ctrl in controls)
            {
                Debug.WriteLine(string.Format("valido {0}", ctrl.GetType().ToString()));
                if (ctrl.Controls.Count != 0 && ctrl.GetType().BaseType != typeof(ExtendedDataGridView))
                    ManageControls(ctrl.Controls);

                if (
                    ctrl.GetType() == typeof(DBCheckBox) ||
                    ctrl.GetType() == typeof(RadioButton) ||
                    ctrl.GetType() == typeof(Button) ||
                    ctrl.GetType() == typeof(ComboBox) ||
                    ctrl.GetType() == typeof(DateTimePicker) ||
                    ctrl.GetType() == typeof(RadarTextBox) ||
                    ctrl.GetType() == typeof(TextBox) ||
                    ctrl.GetType() == typeof(TextBox) ||
                    ctrl.GetType() == typeof(DataGridView) ||
                    ctrl.GetType() == typeof(TabPage) ||
                    ctrl.GetType() == typeof(MaskedTextBox) ||
                    ctrl.GetType() == typeof(NumericTextBox) ||
                    ctrl.GetType() == typeof(NumericTextBox1) ||
                    ctrl.GetType() == typeof(DataGridTextBoxColumn))
                    ctrl.Enabled = enabled;

                if (ctrl.GetType().BaseType == typeof(AFSMaskedTextBox) ||
                            ctrl.GetType() == typeof(AFSMaskedTextBox))
                    ((AFSMaskedTextBox)ctrl).ReadOnly = !enabled;
                else
                    if (ctrl.GetType().BaseType == typeof(NumericTextBox1) ||
                        ctrl.GetType() == typeof(NumericTextBox1))
                        ((NumericTextBox1)ctrl).ReadOnly = !enabled;
                    else
                        if (ctrl.GetType().BaseType == typeof(NumericTextBox) ||
                        ctrl.GetType() == typeof(NumericTextBox))
                            ((NumericTextBox)ctrl).ReadOnly = !enabled;
                        else
                            if (ctrl.GetType().BaseType == typeof(DateTextBox) ||
                            ctrl.GetType() == typeof(DateTextBox))
                                ((DateTextBox)ctrl).ReadOnly = !enabled;
                            else
                                if (ctrl.GetType().BaseType == typeof(TextBox) ||
                                ctrl.GetType() == typeof(TextBox))
                                    ((TextBox)ctrl).ReadOnly = !enabled;
                                else
                                    if (ctrl.GetType().BaseType == typeof(AFSMaskedTextBox) ||
                                    ctrl.GetType() == typeof(AFSMaskedTextBox))
                                        ((AFSMaskedTextBox)ctrl).ReadOnly = !enabled;
                                    else
                                        if (ctrl.GetType().BaseType == typeof(TextBox) ||
                                        ctrl.GetType() == typeof(TextBox))
                                            ((TextBox)ctrl).ReadOnly = !enabled;
                                        else
                                            if (ctrl.GetType().BaseType == typeof(DataGridTextBox) ||
                                            ctrl.GetType() == typeof(DataGridTextBox))
                                                ((DataGridTextBox)ctrl).ReadOnly = !enabled;
                                            else
                                                if (ctrl.GetType().BaseType == typeof(DataGrid) ||
                                                ctrl.GetType() == typeof(DataGrid))
                                                    ((DataGrid)ctrl).ReadOnly = !enabled;
                                                else
                                                    if (ctrl.GetType().BaseType == typeof(LookUpCombo) ||
                                                ctrl.GetType() == typeof(LookUpCombo))
                                                        ((LookUpCombo)ctrl).Enabled = enabled;
                                                    else
                                                        if (ctrl.GetType().BaseType == typeof(ExtendedDataGridView) ||
                                                        ctrl.GetType() == typeof(ExtendedDataGridView))
                                                            ((ExtendedDataGridView)ctrl).ReadOnly = !enabled;
                                                        else
                                                            Debug.WriteLine(ctrl.GetType().ToString());
            }
        }

        #endregion

        #region Enable Disable OperationButton

        private void ManageOperationButton()
        {
            try
            {
                if (dbManager != null)
                {
                    bool enableResult = true;

                    //if (OnEnableToolbarButtons != null)
                    //    enableResult = OnEnableToolbarButtons(tbnGo);
                    //tbnGo.Enabled = BatchStatus != DBMode.Run && enableResult;

                    if (OnEnableToolbarButtons != null)
                        enableResult = OnEnableToolbarButtons(tbnExit);
                    tbnExit.Enabled = BatchStatus != DBMode.Run && enableResult;

                    if (OnEnableToolbarSplitButtons != null)
                        enableResult = OnEnableToolbarSplitButtons(tbnPreview);
                    else
                        enableResult = false;
                    tbnPreview.Enabled = BatchStatus != DBMode.Run && enableResult;
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private void ManageToolbarEvents()
        {
            ManageOperationButton();
            if (controlBinder != null)
                controlBinder.Enable(BatchStatus == DBMode.Browse);

            tssStatus.Text = BatchStatus == DBMode.Run
                                ? Properties.Resources.Doc_Running
                                : Properties.Resources.Doc_Ready;

            tbnGo.Image = BatchStatus == DBMode.Run
                ? Properties.Resources.Stop
                : Properties.Resources.Run;

            tbnGo.Text = BatchStatus == DBMode.Run
                ? Properties.Resources.Doc_Stop
                : Properties.Resources.Doc_Run;
        }

        #endregion

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
        }

        #endregion

        private void DocumentForm_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        #region Print

        protected virtual void OnAddSplitMenuButton()
        {
        }

        protected void AddSplitMenuButton(string text, string tag)
        {
            if (tbnPreview.Tag == null)
                tbnPreview.Tag = tag;

            ToolStripMenuItem mnu = new ToolStripMenuItem(text);
            mnu.Click += new EventHandler(mnu_Click);
            mnu.Tag = tag;
            tbnPreview.DropDownItems.Add(mnu);
        }

        private void mnu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem mnu = (ToolStripMenuItem)sender;
            OnPrintEvent(mnu.Tag != null ? mnu.Tag.ToString() : "");
        }

        #endregion

        private void tbnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void OnPrintEvent(string sender)
        {
            printerForm pf = new printerForm(formName, printerForm.PrintMode.Preview, PrintType.Letter);
            if (OnPrintDocument(sender, pf))
                OpenForm(pf, true);
        }

        private void tbnGo_Click(object sender, EventArgs e)
        {
            if (BatchStatus != DBMode.Run)
                OnGoEvent();
            else
                OnStopEvent();
        }

        private void tbnPrint_ButtonClick(object sender, EventArgs e)
        {
            OnPrintEvent(tbnPreview.Tag != null ? tbnPreview.Tag.ToString() : "");
        }
    }
}